package com.wanji.gateway.model;

import com.wanji.gateway.constant.DeviceStatus;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.Duration;
import java.time.LocalDateTime;

@Data
@AllArgsConstructor
public class DeviceContext {

    private final String deviceId;
    private final String deviceIp;
    private Channel channel;
    private LocalDateTime lastHeartbeatTime;
    private LocalDateTime registerTime;
    private boolean active;


    /**
     * 更新设备连接Channel
     */
    public void updateChannel(Channel channel) {
        this.channel = channel;
        this.active = true;
    }

    /**
     * 更新最后心跳时间
     */
    public void updateHeartbeatTime(LocalDateTime time) {
        this.lastHeartbeatTime = time;
    }

    /**
     * 关闭设备连接
     */
    public void close() {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
        this.active = false;
    }

    /**
     * 获取设备状态
     */
    public DeviceStatus getStatus() {
        if (!active) {
            return DeviceStatus.OFFLINE;
        }

        // 计算心跳间隔
        long secondsSinceHeartbeat = Duration
                .between(lastHeartbeatTime, LocalDateTime.now())
                .getSeconds();

        if (secondsSinceHeartbeat > 60) {
            return DeviceStatus.UNSTABLE;
        }

        return DeviceStatus.ONLINE;
    }
}
